import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:sxw_bluetooth_provider/sxw_bluetooth_provider.dart';
import 'package:sxw_bt_provider_example/button_factory.dart';
import 'package:fast_gbk/fast_gbk.dart';

class ManagerDevicePage extends StatefulWidget {
  final SxwBluetoothProvider provider;

  ManagerDevicePage(this.provider);

  @override
  _ManagerDevicePageState createState() => _ManagerDevicePageState();
}

class _ManagerDevicePageState extends State<ManagerDevicePage> {
  SxwBluetoothProvider get provider => widget.provider;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("管理设备"),
      ),
      body: AnimatedBuilder(
        animation: provider,
        builder: (_, __) => _buildListView(),
      ),
    );
  }

  Widget _buildListView() {
    final devices = provider.devices;
    return ListView.builder(
      itemCount: devices.length,
      itemBuilder: _buildItem,
    );
  }

  Widget _buildItem(BuildContext context, int index) {
    final device = provider.devices[index];
    return ListTile(
      title: Text(device.name ?? ""),
      subtitle: Row(
        children: <Widget>[
          createTextButton("查询状态", () {
            List<int> data = [0x1D, 0x67, 0x34];
            device.writeData(Uint8List.fromList(data));
          }),
          createTextButton(
            "断开",
            () {
              device.disconnect();
            },
          ),
          createTextButton(
            "发送测试数据",
            () {
              device.writeData(gbk.encode("你好\n"));
            },
          ),
        ],
      ),
    );
  }
}
